from functools import wraps

from django.db.models import Max
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
from django.shortcuts import render, redirect

from alipay import AliPay

from datetime import datetime

from django.urls import reverse

from App_AliPay.tools import *
from datetime import datetime, timedelta
from App_User_SigninAndRegister.models import User
from App_AliPay.models import vip


def payconfig():
    return AliPay(appid="2016102700771756",
                  debug=True,
                  app_notify_url="http://127.0.0.1:8000/pay/update/",
                  app_private_key_string=private1,  # 应用私钥
                  alipay_public_key_string=public1,
                  sign_type="RSA2")
def pay(request):
    alipay = payconfig()
    mon = int(request.POST.get("mon"))
    email = request.POST.get("email")
    bookid = request.POST.get("bookid")
    touser = User.objects.get(email=email).userid
    order_string = alipay.api_alipay_trade_page_pay(
        out_trade_no=str(request.session.get("userid")) + str(datetime.now().timestamp()).replace(".", "") + str(
            touser),  # 订单号 - 注 : 每次的订单号不能一致
        # out_trade_no=str(datetime.now().timestamp()).replace(".", ""),
        total_amount=2 * mon,  # 商品价格
        subject='NiceNovelVIP',  # 商品名称
        return_url='http://127.0.0.1:8000/pay/test/' + str(touser)+"/"+bookid,  # 支付成功后 - 重定向自己的网站
        notify_url='http://127.0.0.1:8000/pay/update/'  # 支付成功后 - 异步发送支付结果到回调地址（地址需是服务器地址，否则无法接收到回调结果）
    )
    print(bookid)
    print('http://127.0.0.1:8000/pay/test/' + str(touser)+"/"+bookid)
    pay_url = "https://openapi.alipaydev.com/gateway.do?{}".format(order_string)
    return redirect(pay_url)
def mon(request,bookid):
    print(bookid)
    return render(request, "path01.html",{"bookid":bookid})

def test(request, **data):
    """
     # 支付成功后的回调函数 -- 重定向自己的网站
　　　# 同时在重定向之前会校验此次支付信息是否正确
    :param request:
    :return:
    """

    params = request.GET.dict()
    touser = data["touser"]
    bookid = data["bookid"]
    mon = int(float(params["total_amount"])) / 2
    u = User.objects.get(userid=int(touser))
    u.vipoverdue = datetime.today() + timedelta(days=30 * mon)
    u.vipstatus = "1"
    u.save()
    u.viporder.add(vip.objects.create(order=params["out_trade_no"]))
    request.session["vipstatus"] = "1"
    return redirect(reverse("getbook",kwargs={"bookid":bookid}))


def update(request):
    """
    支付成功后，支付宝向该地址发送的POST请求（用于修改订单状态）
    :param request:
    :return:
    """
    if request.method == 'POST':
        from urllib.parse import parse_qs
        body_str = request.body.decode('utf-8')
        post_data = parse_qs(body_str)
        post_dict = {}
        for k, v in post_data.items():
            post_dict[k] = v[0]
        alipay = payconfig()
        sign = post_dict.pop('sign', None)
        status = alipay.verify(post_dict, sign)
        if status:
            # 1. 获取订单号（获取的订单号是你上面的参数： out_trade_no）
            out_trade_no = post_dict.get('out_trade_no')
            User.objects.get(userid=request.session.get("userid")).viporder.add(vip.objects.create(order=out_trade_no))
            # 2. 根据订单号将数据库中的数据进行更新（修改订单状态）
        return HttpResponse('success')
